package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null); //防止出现id不自动添加
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //PageResult  currentPage 当前页,pageSize每页条数, totalPage 总页数  total总条数
        // 分页数据列表list  next下一页  prev上一页
        //MQL 语句拼接类: 查询封装类
        Query query = new Query();

        //当前页显示数据
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize()
        , Sort.Direction.ASC,"_id");

        return DBHelper.query(query,template,Region.class,pageable,qo);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (!StringUtils.hasLength(region.getId())){
            this.save(region);
        }else {
            this.update(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {

        //方式一;全量更改操作
        /*//查询要更改的region
        Region region = this.get(id);
        //更改hot
        region.setIshot(hot);
        this.update(region);*/

        //方式二: 部分字段更新操作
        //db.region.updateMany({_id:id},{$set:{ishot:hot}})
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,Region.class);
    }

    @Override
    public List<Region> queryHotRegion() {
        //查询热门区域,按序号排列
        return repository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }


}
